package org.datrie;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Main {
	public static void main(String[] args) {
		if (args.length != 1) {
			System.err.println("Se esperaba un argumento");
			return;
		}

		File f = new File(args[0]);
		if (!f.exists()) {
			System.err.println(f + " no existe");
			return;
		}

		BufferedReader input;
		List<String> words;
		try {
			input = new BufferedReader(new FileReader(f));
			String line;
			words = new ArrayList<String>();
			while ((line = input.readLine()) != null)
				words.add(line + "#");
		} catch (IOException e) {
			System.err.println("No pude leer del archivo");
			e.printStackTrace();
			return;
		}

		Collections.sort(words);
		Node root = new Node();
		Datrie.createTrie(root, words, 0);
		System.out.println("Tamano del trie: " + root.size());
		Datrie.transformToReducedTrie(root);
		System.out.println("Transformed to reduced trie");
		System.out.println("Tamano del trie: " + root.size());
//		Datrie.transformToDescendedTrie(root);
//		System.out.println("Transformed to descended trie");
//		System.out.println("Tamano del trie: " + root.size());
		Datrie.makeUnifiedTail(root);
		System.out.println("Made unified tail");
		System.out.println("Tamano del trie: " + root.size());
		Datrie.setBase(root);
		System.out.println("Base is set");
		Datrie.buildBinaryArrays(root);
		System.out.println("Ready");

		try {
			DataOutputStream dataOut = new DataOutputStream(new FileOutputStream("bc.dat"));
			dataOut.write(Datrie.bc);
			dataOut.close();
			dataOut = new DataOutputStream(new FileOutputStream("tail.dat"));
			dataOut.write(Datrie.tail);
			dataOut.close();
		} catch (IOException e) {
			System.err.println("No pude escribir el archivo");
			e.printStackTrace();
		}
	}
}
